package com.example.administrator.caigou51.fragment;


import android.Manifest;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.util.AbFileUtil;
import com.ab.util.AbSharedUtil;
import com.ab.util.AbViewUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.example.administrator.caigou51.EventBusClass.JpushUpdateRedUI;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.activity.AddAgainGoodsActivity;
import com.example.administrator.caigou51.activity.GBaseActivity;
import com.example.administrator.caigou51.activity.LoginActivity;
import com.example.administrator.caigou51.activity.MessageActivity;
import com.example.administrator.caigou51.activity.SearchActivity;
import com.example.administrator.caigou51.bean.AppBean;
import com.example.administrator.caigou51.bean.MainDataBean;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.recyclerCard.basic.MaterialListView;
import com.example.administrator.caigou51.recyclerCard.basic.SuperDIYSwipeRefreshLayout;
import com.example.administrator.caigou51.recyclerCard.basic.SuperSwipeRefresh;
import com.example.administrator.caigou51.recyclerCard.card.MainPart1Card;
import com.example.administrator.caigou51.recyclerCard.card.MainPart2Card;
import com.example.administrator.caigou51.recyclerCard.card.MainPart3Card;
import com.example.administrator.caigou51.recyclerCard.card.basic.AlphaCard;
import com.example.administrator.caigou51.request.BaseResponse;
import com.example.administrator.caigou51.request.ICallBackForRequestServer;
import com.example.administrator.caigou51.request.RequestServerManager;
import com.example.administrator.caigou51.util.ToastUtil;
import com.example.administrator.caigou51.widget.dialog.SweetDialogManager;
import com.example.administrator.caigou51.widget.zxing.CaptureActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.ResponseHandlerInterface;
import com.nineoldandroids.view.ViewHelper;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import de.greenrobot.event.EventBus;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2015/8/11.
 */
public class MainFragment extends BaseFragment implements View.OnClickListener {
    private View holderView;
    private MaterialListView listview;
    private View imageViewGoTop;
   // private SuperDIYSwipeRefreshLayout superSwipeRefresh;
    private boolean isScaled = false;
    private MainDataBean mainDataBean;
    MainPart1Card mainPart1Card;
    RelativeLayout relativeLayout_go_search,relativeLayoutItem;
    private int totel,maxHeight;
    private ImageView imageViewScan,imageViewMessage;
    private View ViewRed;
    int statusBarHeight;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       // EventBus.getDefault().register(this);
        if (holderView == null) {
            holderView = inflater.inflate(R.layout.fragment_main, container, false);
            findViewsById();
            TaskGetMainData(false);
            initView();
            EventBus.getDefault().register(this);
           /* initView();
            getStoreInfo();
            superSwipeRefresh.post(new Runnable() {
                @Override
                public void run() {
                    superSwipeRefresh.setRefreshing(true);
                    TaskGetBanner();
                    TaskGetItem();
                    //TaskActivity();
                    TaskPanicBuying();
                }
            });*/
        }
        ViewGroup parent = (ViewGroup) holderView.getParent();
        if (parent != null) {
            parent.removeView(holderView);
        }
        if (!isScaled) {
            AbViewUtil.scaleContentView((ViewGroup) holderView);
            isScaled = true;
        }
        return holderView;
    }

    private void fillArrayInListView(MainDataBean userBean,boolean isloadMore)
    {
        if (!isloadMore)
        {
            listview.clear();
                mainPart1Card =new MainPart1Card(getActivity());
                mainPart1Card.setMainDataBean(mainDataBean);
                mainPart1Card.setListView(listview);
                listview.add(mainPart1Card);

            AlphaCard alphaCard=new AlphaCard(getActivity());
            alphaCard.setItemHeight(AbViewUtil.scaleValue(getActivity(),114));
            listview.add(alphaCard);

                for (int i=0;i<mainDataBean.getPrefecture().size();i=i+2)
                {

                    MainPart2Card mainPart2Card = new MainPart2Card(getActivity());
                    mainPart2Card.setMainDataBean(mainDataBean);
                    mainPart2Card.setIndex(i);
                    listview.add(mainPart2Card);

                }

                for (int i=0;i<mainDataBean.getHotsell().size();i=i+2)
                {

                    MainPart3Card mainPart3Card = new MainPart3Card(getActivity());
                    mainPart3Card.setMainDataBean(mainDataBean);
                    mainPart3Card.setIndex(i);
                    listview.add(mainPart3Card);

                }
            }

        else
        {


            for (int i=0;i<mainDataBean.getHotsell().size();i=i+2)
            {

                MainPart3Card mainPart3Card = new MainPart3Card(getActivity());
                mainPart3Card.setMainDataBean(mainDataBean);
                mainPart3Card.setIndex(i);
                listview.add(mainPart3Card);

            }

        }

    }
    private void findViewsById()
    {
        listview= (MaterialListView) holderView.findViewById(R.id.listview);
        relativeLayoutItem=(RelativeLayout)holderView.findViewById(R.id.relativeLayoutItem);
        relativeLayout_go_search= (RelativeLayout) holderView.findViewById(R.id.relativeLayout_go_search);relativeLayout_go_search.setOnClickListener(this);
        imageViewScan= (ImageView) holderView.findViewById(R.id.imageViewScan);imageViewScan.setOnClickListener(this);
        imageViewMessage= (ImageView) holderView.findViewById(R.id.imageViewMessage);imageViewMessage.setOnClickListener(this);
        ViewRed=holderView.findViewById(R.id.ViewRed);
        imageViewGoTop=holderView.findViewById(R.id.imageViewGoTop);imageViewGoTop.setOnClickListener(this);
       // superSwipeRefresh= (SuperDIYSwipeRefreshLayout) holderView.findViewById(R.id.superSwipeRefresh);
      //  superSwipeRefresh.setTargetScrollWithLayout(false);
    }

    private void initView() {
        new Handler().postDelayed(new Runnable(){

            public void run() {

                TaskCheckUpdate();

            }

        }, 5000);




        //获取状态栏高度

        if (statusBarHeight==0) {
            Rect frame = new Rect();
            getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            statusBarHeight = frame.top;
        }

        final int marginTop= App.getInstance().screenWidth * 300 / 750+AbViewUtil.scaleValue(getActivity(),88)+statusBarHeight;

        final int xuFuTop=marginTop-AbViewUtil.scaleValue(getActivity(),84);


        RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) relativeLayout_go_search.getLayoutParams();
        params.setMargins(0,marginTop,0,AbViewUtil.scaleValue(getActivity(),20));
        params.height=AbViewUtil.scaleValue(getActivity(),114);
        relativeLayout_go_search.setTag(AbViewUtil.NotScale);
        AbViewUtil.scaleContentView(relativeLayoutItem);
        //置顶列表
        listview.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);



                //设置顶栏的透明度随滑动改变
                //总滑动的距离，dy为正向下滑，dy为负向上滑
                totel += dy;
              //  Log.e("总滑动距离",totel+"");

                // if (alphaCardHide.getView()!=null) {

           //     ViewHelper.setTranslationY(relativeLayout_go_search,-( totel));
                //往上移动是负数，往下是正数，数字越大，距离越大
                //这里的listview有个paddingTop，所以要加上这个高度
                //初次底部出现alpha卡时
                //如果手速太快，则要判断总滑动距离
               /* if (totel==0)
                {
                    ViewHelper.setTranslationY(relativeLayout_go_search,300);
                }*/
                 if (totel>=0 && totel <=xuFuTop)
                {
                    ViewHelper.setTranslationY(relativeLayout_go_search,-( totel));
                    // ViewHelper.setTranslationY(relativeLayoutHide,0);
                }else if (totel>xuFuTop)
                {

                    // ViewHelper.setTranslationY(relativeLayoutHide,-( statusBarHeight+AbViewUtil.scaleValue(getActivity(),250)));
                    ViewHelper.setTranslationY(relativeLayout_go_search,-(xuFuTop));
                }


                //   }

                if (totel < 0)
                    totel = 0;
                // relativeLayoutHide.setVisibility(View.GONE);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }
        });

      /*  superSwipeRefresh.setOnPullRefreshListener(new SuperDIYSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {
                    TaskGetMainData(false);

            }

            @Override
            public void onPullDistance(int distance) {
                // pull distance
            }

            @Override
            public void onPullEnable(boolean enable) {
                     *//*   textView.setText(enable ? "松开刷新" : "下拉刷新");
                        imageView.setVisibility(View.VISIBLE);
                        imageView.setRotation(enable ? 180 : 0);*//*
            }
        });

        superSwipeRefresh
                .setOnPushLoadMoreListener(new SuperDIYSwipeRefreshLayout.OnPushLoadMoreListener() {

                    @Override
                    public void onLoadMore() {
                        TaskGetMainData(true);
                    }

                    @Override
                    public void onPushEnable(boolean enable) {
                        //    footerTextView.setText(enable ? "松开加载" : "上拉加载");
                        //    footerImageView.setVisibility(View.VISIBLE);
                        //    footerImageView.setRotation(enable ? 0 : 180);
                    }

                    @Override
                    public void onPushDistance(int distance) {
                        // TODO Auto-generated method stub

                    }

                });*/

    }

    private void TaskGetMainData(final boolean isloadmore) {
        RequestServerManager.getInstanceDIY().handleMethodDIY((GBaseActivity) getActivity(), listview, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_MainData, Constant.Action.TokenAct_MainData, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_MainData,20+"", 1+""), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                       // JSONObject jsonObject = (JSONObject) result.getData();
                        mainDataBean = JSON.parseObject(result.getData().toString(), MainDataBean.class);
                        GBaseActivity.Xn_ID=mainDataBean.getXn_id();
                        fillArrayInListView(mainDataBean,isloadmore);
                        Log.e("userBean",JSON.toJSONString(mainDataBean));
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    public void onEventMainThread(JpushUpdateRedUI jpushUpdateRedUI) {
        //如果不是在消息页面就添加红点
        if (!((GBaseActivity)getActivity()).getCurrentActivityName(getActivity()).contains("MessageActivity"))
        {

                if (jpushUpdateRedUI.isShowRed)
                {
                    ViewRed.setVisibility(View.VISIBLE);
                }else
                {
                    ViewRed.setVisibility(View.GONE);
                }


        }
    }
    public static final int EXTERNAL_STORAGE_REQ_CODE = 101;

    public void requestPermission(){
        //判断当前Activity是否已经获得了该权限
     /*   if (ContextCompat.checkSelfPermission(getActivity(),
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(getActivity(),"please give me the permission", Toast.LENGTH_SHORT).show();
            } else {
                //进行权限请求
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        EXTERNAL_STORAGE_REQ_CODE);
            }
        }
        ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE);*/

           // ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, EXTERNAL_STORAGE_REQ_CODE);
        //    String[] perms = {Manifest.permission.CAMERA};
         /*   if (EasyPermissions.hasPermissions(getActivity(), perms)) {
                Intent intent5 = new Intent(getActivity(),CaptureActivity.class);
                getActivity().startActivity(intent5);
            } else {
                EasyPermissions.requestPermissions(this, "扫一扫需要摄像头权限", EXTERNAL_STORAGE_REQ_CODE, perms);
            }*/
        //EasyPermissions.requestPermissions(this, "扫一扫需要摄像头权限", EXTERNAL_STORAGE_REQ_CODE, perms);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.imageViewGoTop:
                listview.smoothScrollToPosition(0);
                break;
            case R.id.imageViewScan:
              //  requestPermission();
                  Intent intent5 = new Intent(getActivity(),CaptureActivity.class);
                  getActivity().startActivity(intent5);

              //  TaskCheckUpdate();
                break;
            case R.id.imageViewMessage:
                if (App.getUserBean()==null)
                {
                    Intent intent=new Intent(getActivity(), LoginActivity.class);
                    getActivity().startActivity(intent);
                }else
                {
                    //card.setShowRed(false);
                    // card.getListView().getAdapter().notifyDataSetChanged();

                    Intent intent = new Intent(getActivity(), MessageActivity.class);
                    getActivity().startActivity(intent);
                    ViewRed.setVisibility(View.GONE);
                }
                break;
            case R.id.relativeLayout_go_search:
                Intent intent=new Intent(getActivity(), SearchActivity.class);
                getActivity().startActivity(intent);
                break;
        }
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mainDataBean==null)
        {
            TaskGetMainData(false);
        }
       //is_verified 0未验证，1已验证
        if (isVisibleToUser) {
            if (App.getUserBean()!=null && App.getUserBean().getIs_verified()==App.PassValue) {
                TaskIsHuiYuan(false);
            }
            //相当于Fragment的onResume
        } else {
            //相当于Fragment的onPause
        }
    }

    public void TaskIsHuiYuan(final boolean isloadmore) {
        RequestServerManager.getInstanceDIY().handleMethodDIY(null, null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_isVerified, Constant.Action.Action_isVerified, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_isVerified, App.getUserBean().getUserid(),App.getUserBean().getSession_id()), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                       App.getUserBean().setIs_verified(1);
                       App.saveUserBean(App.getUserBean());

                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }
    public void TaskCheckUpdate() {


            RequestServerManager.getInstanceDIY().handleMethodDIY(null, null, false, null,
                    Constant.getRootUrl() + Constant.Action.Action_getAppInfo, Constant.Action.Action_getAppInfo, RequestServerManager.getInstanceDIY().
                            getRequestParams(Constant.Action.Action_getAppInfo), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                        @Override
                        public void onSuccess(BaseResponse result) {
                            final AppBean appBean = JSON.parseObject(result.getData().toString(), AppBean.class);
                            PackageManager pm = getActivity().getPackageManager();
                            PackageInfo pi =null;
                            try {
                                pi = pm.getPackageInfo(getActivity().getPackageName(),PackageManager.GET_CONFIGURATIONS);
                            } catch (PackageManager.NameNotFoundException e) {
                                e.printStackTrace();
                            }
                            if (pi!=null && appBean!=null) {
                                int serverCode = Integer.parseInt(appBean.getApp_android_version());
                                if (serverCode>pi.versionCode)
                                {

                                    SweetDialogManager.getInstance().showDialogByUpdateApk((GBaseActivity) getActivity(), "发现新版本了", appBean.getApp_android_upgrade(), false, false, new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                        }
                                    }, new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                            TaskDownApk(appBean);
                                        }
                                    });
                                }
                            }

                        }

                        @Override
                        public void onFail(int type, String errorMsg, String json) {

                        }
                    });



     //   SweetDialogManager.getInstance().showDialogByCustomImage((GBaseActivity) getActivity(),"发现新版本了","1.优化程序流畅性\n2.增加扫码功能",false,false,R.drawable.icon_51caiyao);
    }
    public void TaskDownApk(AppBean appBean) {



        initDialog();
        AsyncHttpClient httpClient =  new AsyncHttpClient();
        httpClient.setTimeout(20000);
        httpClient.get(appBean.getApp_android_pkg(), new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Log.e("onSuccess11","onSuccess");
                String SavePath = Environment.getExternalStorageDirectory().toString() + "/DCIM/";
                progressDialog.cancel();
                File downFile=byte2File(responseBody,SavePath,"caiyaowang51.APK");
                if (downFile==null)
                {
                    ToastUtil.showToast("亲,请到设置里把储存权限开放");
                }else {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(downFile),
                            "application/vnd.android.package-archive");
                    getActivity().startActivity(intent);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("onFailure11","onFailure");
                Log.e("onFailure111",error.getMessage().toString());
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                Log.e("onProgress11",bytesWritten+"");
                super.onProgress(bytesWritten, totalSize);
                progressDialog.setProgress((int)bytesWritten);
                progressDialog.setMax((int)totalSize);
            }
        });

    }
    public static File byte2File(byte[] buf, String filePath, String fileName)
    {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try
        {
            File dir = new File(filePath);
            if (!dir.exists())
            {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return  null;
        }

        finally
        {
            if (bos != null)
            {
                try
                {
                    bos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
    ProgressDialog progressDialog;
    private void initDialog()
    {
        progressDialog = new ProgressDialog(getActivity());    //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        progressDialog.setProgress(0);
        progressDialog.show();
    }

/*    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Intent intent5 = new Intent(getActivity(),CaptureActivity.class);
        getActivity().startActivity(intent5);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ToastUtil.showToast("扫一扫需要开启摄像头的权限");
    }*/
}


